//
//  DMLifecycleManager.m
//  DualMediationSDK
//
//  Created by DualMediation on 2024/01/01.
//  Copyright © 2024 DualMediation. All rights reserved.
//

#import "DMLifecycleManager.h"
#import "../Utils/Logger/IMLogUtils.h"
#import "../API/Facebook/DMFacebookTypes.h"
#import "../AD/Common/DMAdDelegate.h"
#import "DMLifecycle/Core/DMLifecycleDelegateRegistry.h"
#import "DMLifecycle/Core/DMLifecycleStateManager.h"
#import "DMLifecycle/Core/DMLifecycleEventDispatcher.h"
#import "DMLifecycle/Callback/DMLifecycleCallbackManager.h"
#import "DMLifecycle/Callback/DMFacebookCallbackForwarder.h"
#import "DMATTManager.h"
#import "DMFirebaseManager.h"
#import "DualMediationSDKPublic.h"
#import "DualMediationMAXSplashManager.h"
#import "DMThinkingManager.h"
#import "DMFacebookManager.h"

#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#endif

#pragma mark - 生命周期管理器实现

@interface DMLifecycleManager ()

// 核心组件
@property (nonatomic, strong) DMLifecycleDelegateRegistry *delegateRegistry;
@property (nonatomic, strong) DMLifecycleStateManager *stateManager;
@property (nonatomic, strong) DMLifecycleEventDispatcher *eventDispatcher;
@property (nonatomic, strong) DMLifecycleCallbackManager *callbackManager;
@property (nonatomic, strong) DMFacebookCallbackForwarder *facebookForwarder;

// SDK状态管理
@property (nonatomic, assign) UIViewController *currentViewController;
@property (nonatomic, assign) BOOL sdkInitialized;
@property (nonatomic, strong) NSMutableDictionary *savedInstanceState;
@property (nonatomic, strong) NSMutableArray *notificationObservers;

@end

@implementation DMLifecycleManager

static DMLifecycleManager *_sharedManager = nil;
static dispatch_once_t onceToken;

#pragma mark - 单例实现

+ (instancetype)sharedManager {
    dispatch_once(&onceToken, ^{
        _sharedManager = [[self alloc] init];
    });
    return _sharedManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 初始化核心组件
        _delegateRegistry = [DMLifecycleDelegateRegistry sharedRegistry];
        _stateManager = [DMLifecycleStateManager sharedManager];
        _eventDispatcher = [DMLifecycleEventDispatcher sharedDispatcher];
        _callbackManager = [DMLifecycleCallbackManager sharedManager];
        _facebookForwarder = [DMFacebookCallbackForwarder sharedForwarder];
        
        // 初始化SDK状态
        _sdkInitialized = NO;
        _savedInstanceState = [NSMutableDictionary dictionary];
        _notificationObservers = [NSMutableArray array];
        
        // 初始化Firebase Core
        [[DMFirebaseManager shareFirebaseManager] initializeFirebaseIfNeeded];
        
        [self setupNotificationObservers];
        [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 生命周期管理器初始化完成，所有组件已加载"];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 便捷属性访问

- (DMLifecycleState)currentLifecycleState {
    return self.stateManager.currentState;
}

- (DMLifecycleState)previousLifecycleState {
    return self.stateManager.previousState;
}

- (BOOL)isSDKInitialized {
    return self.sdkInitialized;
}

#pragma mark - 通知观察者设置

- (void)setupNotificationObservers {
#if TARGET_OS_IPHONE
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    // 应用生命周期通知
    [center addObserver:self
               selector:@selector(handleApplicationDidBecomeActiveNotification:)
                   name:UIApplicationDidBecomeActiveNotification
                 object:nil];
    
    [center addObserver:self
               selector:@selector(handleApplicationWillResignActiveNotification:)
                   name:UIApplicationWillResignActiveNotification
                 object:nil];
    
    [center addObserver:self
               selector:@selector(handleApplicationDidEnterBackgroundNotification:)
                   name:UIApplicationDidEnterBackgroundNotification
                 object:nil];
    
    [center addObserver:self
               selector:@selector(handleApplicationWillEnterForegroundNotification:)
                   name:UIApplicationWillEnterForegroundNotification
                 object:nil];
    
    [center addObserver:self
               selector:@selector(handleApplicationWillTerminateNotification:)
                   name:UIApplicationWillTerminateNotification
                 object:nil];
    
    [center addObserver:self
               selector:@selector(handleApplicationDidReceiveMemoryWarningNotification:)
                   name:UIApplicationDidReceiveMemoryWarningNotification
                 object:nil];
#endif
    
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] iOS生命周期通知观察者设置完成"];
}

#pragma mark - 应用生命周期通知处理

- (void)handleApplicationDidBecomeActiveNotification:(NSNotification *)notification {
    [self applicationDidBecomeActive:[UIApplication sharedApplication]];
}

- (void)handleApplicationWillResignActiveNotification:(NSNotification *)notification {
    [self applicationWillResignActive:[UIApplication sharedApplication]];
}

- (void)handleApplicationDidEnterBackgroundNotification:(NSNotification *)notification {
    [self applicationDidEnterBackground:[UIApplication sharedApplication]];
}

- (void)handleApplicationWillEnterForegroundNotification:(NSNotification *)notification {
    [self applicationWillEnterForeground:[UIApplication sharedApplication]];
}

- (void)handleApplicationWillTerminateNotification:(NSNotification *)notification {
    [self applicationWillTerminate:[UIApplication sharedApplication]];
}

- (void)handleApplicationDidReceiveMemoryWarningNotification:(NSNotification *)notification {
    [self applicationDidReceiveMemoryWarning:[UIApplication sharedApplication]];
}

#pragma mark - 公共接口实现

- (void)registerSDKListener:(UIViewController *)viewController delegate:(id<DMSDKLifecycleDelegate>)delegate {
    if (!viewController) {
        [IMLogUtils error:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ❌ 注册SDK监听器失败：viewController为空"];
        return;
    }
    
    if (!delegate) {
        [IMLogUtils error:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ❌ 注册SDK监听器失败：delegate为空"];
        return;
    }
    
    self.currentViewController = viewController;
    
    // 使用代理注册中心注册SDK回调代理
    [self.delegateRegistry registerSDKCallbackDelegate:delegate];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ✅ SDK监听器注册成功"];
    
    // 初始化Firebase消息服务
    [self initFirebaseMessage:viewController];
    
    // 初始化Firebase消息推送
    [[DMFirebaseManager shareFirebaseManager] initializeFirebaseMessagingWithCompletion:^(IMFCMPushResult *result) {
        if (result.success) {
            [IMLogUtils info:IMLogTagFirebase format:@"Firebase消息推送初始化成功"];
        } else {
            [IMLogUtils error:IMLogTagFirebase format:@"Firebase消息推送初始化失败: %@", result.errorMessage ?: @"未知错误"];
        }
    }];
    
    // 标记SDK已初始化
    self.sdkInitialized = YES;
}

- (void)initFirebaseMessage:(UIViewController *)viewController {
    if (!viewController) {
        [IMLogUtils error:IMLogTagFirebase format:@"初始化Firebase消息失败：viewController为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagFirebase format:@"开始初始化Firebase消息服务"];
    
    // 确保Firebase Core已初始化
    [[DMFirebaseManager shareFirebaseManager] initializeFirebaseIfNeeded];
    
    // 初始化Firebase消息推送（带目标页面）
    [[DMFirebaseManager shareFirebaseManager] initializeFirebaseMessagingWithTargetViewController:[viewController class] completion:^(IMFCMPushResult *result) {
        if (result.success) {
            [IMLogUtils info:IMLogTagFirebase format:@"Firebase消息服务初始化完成"];
        } else {
            [IMLogUtils error:IMLogTagFirebase format:@"Firebase消息服务初始化失败: %@", result.errorMessage ?: @"未知错误"];
        }
    }];
}

#pragma mark - iOS标准生命周期方法实现

- (BOOL)applicationDidFinishLaunching:(UIApplication *)application withOptions:(nullable NSDictionary *)launchOptions {
    // 在 Release 环境自动关闭所有日志相关输出（打印、监听、写文件、上传）
    #ifdef DEBUG
    [IMLogUtils enableLog:YES];
    IMLogConfig *cfg = [IMLogUtils currentConfig];
    cfg.enableConsoleLog = YES;
    cfg.enableFileLog = YES;
    cfg.enableUpload = NO;
    #else
    [IMLogUtils enableLog:NO];
    IMLogConfig *cfg = [IMLogUtils currentConfig];
    cfg.enableConsoleLog = NO;
    cfg.enableFileLog = NO;
    cfg.enableUpload = NO;
    [IMLogUtils removeLogMonitor];
    #endif
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 🚀 应用启动完成"];
    [DualMediationSDKPublic IninSDKWithCompletion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            [IMLogUtils info:IMLogTagSDKInit format:@"✅ SDK初始化成功"];
            
            [[DMFirebaseManager shareFirebaseManager] initializeFirebaseIfNeeded];
            [IMLogUtils info:IMLogTagFirebase format:@"应用启动时Firebase Core初始化完成"];
            
            // 初始化数数（ThinkingData）SDK
            [[DMThinkingManager shareThinkingManager] thinkingConfig];
            
            // 初始化 Adjust SDK（由管理器内部读取配置）
            id adjustManager = [NSClassFromString(@"DMAdjustManager") respondsToSelector:@selector(sharedManager)] ? [NSClassFromString(@"DMAdjustManager") performSelector:@selector(sharedManager)] : nil;
            if (adjustManager && [adjustManager respondsToSelector:@selector(AdjustConfigInit)]) {
                [adjustManager performSelector:@selector(AdjustConfigInit)];
                [IMLogUtils info:IMLogTagSDKInit format:@"Adjust SDK初始化完成"];
            } else {
                [IMLogUtils warning:IMLogTagSDKInit format:@"AdjustManager 不可用，跳过初始化"];
            }
            
            BOOL fbInit = [DMFacebookManager initializeWithApplication:application launchOptions:launchOptions ?: @{}];
            if (fbInit) {
                [IMLogUtils info:IMLogTagAPI format:@"Facebook SDK初始化完成"];
            } else {
                [IMLogUtils error:IMLogTagAPI format:@"Facebook SDK初始化失败"];
            }
        } else {
            [IMLogUtils error:IMLogTagSDKInit format:@"❌ SDK初始化失败: %@", error.localizedDescription];
            [[DMFirebaseManager shareFirebaseManager] initializeFirebaseIfNeeded];
            [IMLogUtils info:IMLogTagFirebase format:@"应用启动时Firebase Core初始化完成"];
            
            // 初始化数数（ThinkingData）SDK
            [[DMThinkingManager shareThinkingManager] thinkingConfig];
            
            // 初始化 Adjust SDK（由管理器内部读取配置）
            id adjustManager = [NSClassFromString(@"DMAdjustManager") respondsToSelector:@selector(sharedManager)] ? [NSClassFromString(@"DMAdjustManager") performSelector:@selector(sharedManager)] : nil;
            if (adjustManager && [adjustManager respondsToSelector:@selector(AdjustConfigInit)]) {
                [adjustManager performSelector:@selector(AdjustConfigInit)];
                [IMLogUtils info:IMLogTagSDKInit format:@"Adjust SDK初始化完成"];
            } else {
                [IMLogUtils warning:IMLogTagSDKInit format:@"AdjustManager 不可用，跳过初始化"];
            }
            
            BOOL fbInit = [DMFacebookManager initializeWithApplication:application launchOptions:launchOptions ?: @{}];
            if (fbInit) {
                [IMLogUtils info:IMLogTagAPI format:@"Facebook SDK初始化完成"];
            } else {
                [IMLogUtils error:IMLogTagAPI format:@"Facebook SDK初始化失败"];
            }
        }
    }];
    if (launchOptions) {
        [self.savedInstanceState addEntriesFromDictionary:launchOptions];
    }
    
    // 初始化Firebase Core
    
    
    // 初始化DualMediationSDK
    
    
    [[DualMediationMAXSplashManager sharedSplashManager]setSplashAdDisable:NO];
    
    // 使用状态管理器转换状态（仅在合适时设置为 Launching，避免 Active -> Launching 的无效回退）
    DMLifecycleState currentState = [self.stateManager getCurrentState];
    if (!self.stateManager.isInitialized ||
        currentState == DMLifecycleStateUnknown ||
        currentState == DMLifecycleStateLaunching) {
        [self.stateManager transitionToState:DMLifecycleStateLaunching];
    } else {
        [IMLogUtils warning:IMLogTagSDKInit
                      format:@"📱 [DMLifecycleManager] ⏭️ 跳过设置Launching，当前状态=%@，避免无效回退",
         DMLifecycleStateDescription(currentState)];
    }
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventDidFinishLaunching userInfo:launchOptions];
    
    // 标记SDK已初始化
    self.sdkInitialized = YES;
    
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 📱 应用变为活跃状态"];
    
    // 使用状态管理器转换状态
    [self.stateManager transitionToState:DMLifecycleStateActive];
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventDidBecomeActive userInfo:nil];
    
    // 通知DualMediationSDKPublic应用变为活跃
    // 这里可以调用相关的激活方法
    
    // 请求ATT权限 - 在应用变为活跃状态时执行
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 🔒 开始请求ATT权限"];
    [[DMATTManager sharedManager] requestATTPermissionWithCompletion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ✅ ATT权限请求完成"];
        } else {
            [IMLogUtils warning:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ⚠️ ATT权限请求失败: %@", error.localizedDescription ?: @"未知错误"];
        }
    }];
    
    [[DualMediationMAXSplashManager sharedSplashManager]showSplash];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ⏸️ 应用将要失去活跃状态"];
    
    // 使用状态管理器转换状态
    [self.stateManager transitionToState:DMLifecycleStateInactive];
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventWillResignActive userInfo:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 🌙 应用进入后台"];
    
    // 使用状态管理器转换状态
    [self.stateManager transitionToState:DMLifecycleStateBackground];
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventDidEnterBackground userInfo:nil];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ☀️ 应用将要进入前台"];
    
    // 使用状态管理器转换状态
    [self.stateManager transitionToState:DMLifecycleStateForeground];
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventWillEnterForeground userInfo:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 💥 应用将要终止"];
    
    // 使用状态管理器转换状态
    [self.stateManager transitionToState:DMLifecycleStateTerminating];
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventWillTerminate userInfo:nil];
    
    // 清理资源
    [self.savedInstanceState removeAllObjects];
    self.currentViewController = nil;
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    [IMLogUtils warning:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ⚠️ 收到内存警告"];
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventDidReceiveMemoryWarning userInfo:nil];
}

- (void)applicationDidReceiveRemoteNotification:(UIApplication *)application userInfo:(NSDictionary *)userInfo {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 📬 收到远程推送通知: %@", userInfo];
    
    // 检查是否为Firebase通知并处理
    if ([[DMFirebaseManager shareFirebaseManager] isFCMNotification:userInfo]) {
        [IMLogUtils info:IMLogTagFirebase format:@"处理Firebase推送通知"];
        [[DMFirebaseManager shareFirebaseManager] handleNotificationTap:userInfo viewController:self.currentViewController];
    }
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventDidReceiveRemoteNotification userInfo:userInfo];
    
    // 使用回调管理器处理推送消息点击
    if (userInfo[@"messageId"]) {
        NSString *messageId = userInfo[@"messageId"];
        [self.callbackManager triggerPushMessageClick:messageId];
    }
}

- (void)applicationDidReceiveLocalNotification:(UIApplication *)application notification:(UILocalNotification *)notification {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 📱 收到本地通知: %@", notification.alertBody];
    
    NSDictionary *userInfo = notification.userInfo;
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventDidReceiveLocalNotification userInfo:userInfo];
}

- (BOOL)applicationOpenURL:(UIApplication *)application url:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 🔗 打开URL: %@", url.absoluteString];
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    if (url) userInfo[@"url"] = url.absoluteString;
    if (options) userInfo[@"options"] = options;
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventOpenURL userInfo:userInfo];
    
    [DMFacebookManager handleOpenURL:application url:url options:options];
    
    // 使用Facebook回调转发器处理URL
    return [self.facebookForwarder handleOpenURL:url options:options];
}

- (BOOL)applicationContinueUserActivity:(UIApplication *)application userActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * _Nullable restorableObjects))restorationHandler {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 🔄 继续用户活动: %@", userActivity.activityType];
    
    NSDictionary *userInfo = @{
        @"activityType": userActivity.activityType ?: @"",
        @"webpageURL": userActivity.webpageURL ? userActivity.webpageURL.absoluteString : @"",
        @"userInfo": userActivity.userInfo ?: @{}
    };
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventContinueUserActivity userInfo:userInfo];
    
    // 使用Facebook回调转发器处理用户活动
    return [self.facebookForwarder handleContinueUserActivity:userActivity restorationHandler:restorationHandler];
}

- (void)onNewIntent:(NSDictionary *)userInfo {
    if (!userInfo) {
        [IMLogUtils warning:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ⚠️ onNewIntent调用时userInfo为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 🔄 处理新的Intent: %@", userInfo];
    
    // 使用回调管理器处理推送消息点击
    if (userInfo[@"messageId"]) {
        NSString *messageId = userInfo[@"messageId"];
        [self.callbackManager triggerPushMessageClick:messageId];
    }
}

- (void)onActivityResult:(NSInteger)requestCode resultCode:(NSInteger)resultCode data:(nullable NSDictionary *)data {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 📋 处理Activity结果: requestCode=%ld, resultCode=%ld", (long)requestCode, (long)resultCode];
    
    // 使用Facebook回调转发器处理各种Activity结果
    switch (requestCode) {
        case 1001: // Facebook登录
            [self.facebookForwarder handleFacebookLoginResult:resultCode data:data];
            break;
        case 1002: // 支付结果
            [self.callbackManager triggerPurchaseResult:resultCode data:data];
            break;
        default:
            [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 未知的requestCode: %ld", (long)requestCode];
            break;
    }
}

- (void)onRequestPermissionsResult:(NSInteger)requestCode permissions:(NSArray<NSString *> *)permissions grantResults:(NSArray<NSNumber *> *)grantResults {
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 🔐 处理权限请求结果: requestCode=%ld", (long)requestCode];
    
    for (NSInteger i = 0; i < permissions.count && i < grantResults.count; i++) {
        NSString *permission = permissions[i];
        BOOL granted = [grantResults[i] boolValue];
        [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] 权限 %@: %@", permission, granted ? @"已授权" : @"被拒绝"];
    }
}

#pragma mark - 私有方法

// 私有方法已迁移到对应的组件中
// - Facebook相关处理已迁移到DMFacebookCallbackForwarder
// - 购买相关处理已迁移到DMLifecycleCallbackManager

#pragma mark - 便捷方法

+ (void)registerSDKListenerWithViewController:(UIViewController *)viewController delegate:(id<DMSDKLifecycleDelegate>)delegate {
    [[DMLifecycleManager sharedManager] registerSDKListener:viewController delegate:delegate];
}

- (void)onResume:(UIViewController *)viewController {
    if (!viewController) {
        [IMLogUtils warning:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ⚠️ onResume调用时viewController为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ▶️ 应用恢复活动"];
    
    self.currentViewController = viewController;
    
    // 使用状态管理器转换状态
    [self.stateManager transitionToState:DMLifecycleStateActive];
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventDidBecomeActive userInfo:nil];
}

- (void)onPause:(UIViewController *)viewController {
    if (!viewController) {
        [IMLogUtils warning:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ⚠️ onPause调用时viewController为空"];
        return;
    }
    
    [IMLogUtils info:IMLogTagSDKInit format:@"📱 [DMLifecycleManager] ⏸️ 应用暂停活动"];
    
    // 使用状态管理器转换状态
    [self.stateManager transitionToState:DMLifecycleStateInactive];
    
    // 使用事件分发器分发事件
    [self.eventDispatcher dispatchLifecycleEvent:DMLifecycleEventWillResignActive userInfo:nil];
}

+ (void)onResumeWithViewController:(UIViewController *)viewController {
    [[DMLifecycleManager sharedManager] onResume:viewController];
}

+ (void)onPauseWithViewController:(UIViewController *)viewController {
    [[DMLifecycleManager sharedManager] onPause:viewController];
}

+ (void)onNewIntentWithUserInfo:(NSDictionary *)userInfo {
    [[DMLifecycleManager sharedManager] onNewIntent:userInfo];
}

+ (void)onActivityResultWithRequestCode:(NSInteger)requestCode resultCode:(NSInteger)resultCode data:(nullable NSDictionary *)data {
    [[DMLifecycleManager sharedManager] onActivityResult:requestCode resultCode:resultCode data:data];
}

+ (void)onRequestPermissionsResultWithRequestCode:(NSInteger)requestCode permissions:(NSArray<NSString *> *)permissions grantResults:(NSArray<NSNumber *> *)grantResults {
    [[DMLifecycleManager sharedManager] onRequestPermissionsResult:requestCode permissions:permissions grantResults:grantResults];
}

#pragma mark - 生命周期监听器管理便捷方法

- (void)addLifecycleEventListener:(id<DMLifecycleEventListener>)listener {
    [self.eventDispatcher addLifecycleEventListener:listener];
}

- (void)removeLifecycleEventListener:(id<DMLifecycleEventListener>)listener {
    [self.eventDispatcher removeLifecycleEventListener:listener];
}

- (BOOL)isActive {
    return [self.stateManager isActive];
}

- (BOOL)isForeground {
    return [self.stateManager isForeground];
}

- (BOOL)isBackground {
    return [self.stateManager isBackground];
}

#pragma mark - 回调方法（已迁移到组件）

// Facebook登录回调方法已迁移到DMFacebookCallbackForwarder
// 使用 self.facebookForwarder 来处理Facebook相关回调

// 产品和购买相关回调方法已迁移到DMLifecycleCallbackManager
// 使用 self.callbackManager 来处理产品和购买相关回调

// 其他回调触发方法已迁移到DMLifecycleCallbackManager
// 使用 self.callbackManager 来处理评价、分享、BMS配置、推送消息等回调

// Facebook回调转发方法已迁移到DMFacebookCallbackForwarder
// URL和用户活动处理方法已迁移到DMFacebookCallbackForwarder

#pragma mark - Facebook回调转发方法

- (void)forwardFacebookLoginSuccess:(NSDictionary *)userInfo {
    [IMLogUtils info:IMLogTagAPI format:@"📘 [DMLifecycleManager] 转发Facebook登录成功回调"];
    
    // 创建DMLoginResponse对象
    DMLoginResponse *response = [[DMLoginResponse alloc] init];
    response.success = YES;
    response.userInfo = userInfo;
    
    // 使用Facebook回调转发器转发登录成功
    [self.facebookForwarder forwardLoginSuccess:response];
}

- (void)forwardFacebookLoginError:(NSError *)error {
    [IMLogUtils error:IMLogTagError format:@"❌ [DMLifecycleManager] 转发Facebook登录失败回调: %@", error.localizedDescription];
    
    // 使用Facebook回调转发器转发登录失败
    [self.facebookForwarder forwardLoginFailure:error];
}

- (void)forwardFacebookLoginCancel {
    [IMLogUtils info:IMLogTagAPI format:@"📘 [DMLifecycleManager] 转发Facebook登录取消回调"];
    
    // 使用Facebook回调转发器转发登录取消
    [self.facebookForwarder forwardLoginCancel];
}

- (void)forwardFacebookUserInfoSuccess:(NSDictionary *)userInfo {
    [IMLogUtils info:IMLogTagAPI format:@"📘 [DMLifecycleManager] 转发Facebook用户信息获取成功回调"];
    
    // 使用Facebook回调转发器转发用户信息获取成功
    [self.facebookForwarder forwardGenericCallback:@"userInfoSuccess" data:userInfo];
}

- (void)forwardFacebookUserInfoError:(NSError *)error {
    [IMLogUtils error:IMLogTagError format:@"❌ [DMLifecycleManager] 转发Facebook用户信息获取失败回调: %@", error.localizedDescription];
    
    // 使用Facebook回调转发器转发用户信息获取失败
    [self.facebookForwarder forwardGenericCallback:@"userInfoError" data:error];
}

- (void)forwardFacebookShareComplete:(BOOL)success message:(NSString *)message {
    [IMLogUtils info:IMLogTagAPI format:@"📘 [DMLifecycleManager] 转发Facebook分享完成回调: success=%@, message=%@", success ? @"YES" : @"NO", message];
    
    // 创建分享结果数据
    NSDictionary *shareData = @{
        @"success": @(success),
        @"message": message ?: @""
    };
    
    // 使用Facebook回调转发器转发分享完成
    if (success) {
        [self.facebookForwarder forwardShareSuccess:shareData];
    } else {
        NSError *shareError = [NSError errorWithDomain:@"FacebookShareError" code:1001 userInfo:@{NSLocalizedDescriptionKey: message ?: @"分享失败"}];
        [self.facebookForwarder forwardShareFailure:shareError];
    }
}

#pragma mark - Firebase管理方法实现

- (void)initializeFirebaseIfNeeded {
    [[DMFirebaseManager shareFirebaseManager] initializeFirebaseIfNeeded];
    [IMLogUtils info:IMLogTagFirebase format:@"Firebase Core初始化检查完成"];
}

- (BOOL)isFCMInitialized {
    return [[DMFirebaseManager shareFirebaseManager] isFCMInitialized];
}

- (void)initializeFirebaseMessagingWithCompletion:(nullable IMFCMPushCompletionBlock)completion {
    [[DMFirebaseManager shareFirebaseManager] initializeFirebaseMessagingWithCompletion:completion];
}

- (void)initializeFirebaseMessagingWithTargetViewController:(Class)targetViewControllerClass completion:(nullable IMFCMPushCompletionBlock)completion {
    [[DMFirebaseManager shareFirebaseManager] initializeFirebaseMessagingWithTargetViewController:targetViewControllerClass completion:completion];
}

- (nullable NSString *)getCurrentFCMToken {
    return [[DMFirebaseManager shareFirebaseManager] getCurrentFCMToken];
}

- (void)getFCMTokenWithCompletion:(IMFCMPushCompletionBlock)completion {
    [[DMFirebaseManager shareFirebaseManager] getFCMTokenWithCompletion:completion];
}

- (void)requestNotificationPermissionWithCompletion:(void(^)(BOOL granted, NSError * _Nullable error))completion {
    [[DMFirebaseManager shareFirebaseManager] requestNotificationPermissionWithCompletion:completion];
}

- (void)handleNotificationTap:(NSDictionary *)userInfo {
    [[DMFirebaseManager shareFirebaseManager] handleNotificationTap:userInfo];
}

- (void)handleNotificationTap:(NSDictionary *)userInfo viewController:(UIViewController *)viewController {
    [[DMFirebaseManager shareFirebaseManager] handleNotificationTap:userInfo viewController:viewController];
}

- (BOOL)isFCMNotification:(NSDictionary *)userInfo {
    return [[DMFirebaseManager shareFirebaseManager] isFCMNotification:userInfo];
}

@end
